package net.mihome.app.adapter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.mihome.app.bean.RssResource;
import net.mihome.app.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class RssResourceAdapter extends BaseAdapter {
	private List<RssResource> list;
	private Context context;
	public List<String> checkdList=new ArrayList<String>();
	public RssResourceAdapter(Context context,List<RssResource> list,List<String> checkeds){
		this.checkdList=checkeds;
		this.context=context;
		this.list=list;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return this.list.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return list.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return list.get(arg0).getId();
	}

	/**
     * 下面是重要代码
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
	        LayoutInflater _LayoutInflater=LayoutInflater.from(this.context);
	        convertView=_LayoutInflater.inflate(R.layout.rss_add_item, null);
	        if(convertView!=null)
	        {
	        	CheckBox item_cheBox=(CheckBox) convertView.findViewById(R.id.rss_add_item_checkbox);
	        	String titleString=list.get(position).getTitle();
	        	item_cheBox.setText(titleString);
	        	if(this.checkdList.contains(titleString)){
	        		item_cheBox.setChecked(true);
	        	}
	        	setOnclikOnCheckBox(item_cheBox);
	        }
        return convertView;
    }
    /**
     * 为单个checkbox添加点击事件
     * */
    public void setOnclikOnCheckBox(CheckBox checkBox){
    	checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    		@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				// TODO Auto-generated method stub
				// TODO Auto-generated method stub
				String titleString=arg0.getText().toString();
				if(arg1){
					checkdList.add(titleString);
				}else{
					Iterator<String> iterator=checkdList.iterator();
					while(iterator.hasNext()){
						String str=iterator.next();
						if(str.equals(titleString)){
							iterator.remove();
						}
					}
				}
			}
		});
    }
}
